import re

from flask import Flask, session, render_template, redirect, Blueprint, request
from config import Config
from db import db
from views.page import page
from views.user import user

app = Flask(__name__)
# 读取配置信息
app.config.from_object(Config)
# 解决中文乱码
app.config["JSON_AS_ASCII"] = False
# 设置上传文件大小
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024
# 设置上传文件保存路径
app.config["UPLOAD_FOLDER"] = r"E:/小白毕设/链家网房屋数据分析/static/upload"

# 加载flask app
db.init_app(app)

# 注册蓝图
app.register_blueprint(page.page_bp)
app.register_blueprint(user.user_bp)


# 跳转到登录页
@app.route("/")
def index():  # put application's code here
    return redirect("/user/login")


# 请求拦截
@app.before_request
def before_request():
    pat = re.compile(r"^/static/.*")
    if pat.match(request.path):
        return None
    if request.path == "/user/login":
        return None
    if request.path == "/user/register":
        return None
    username = session.get("username")
    if username is not None:
        return None

    return redirect("/user/login")


# 错误处理
@app.route("/<path:path>")
def catch_all(path):
    return render_template("404.html")


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5210, debug=True)
